<template>
  <div class="bind-productm-odel">
    <el-row style="paddingBottom: 0">
      <el-col :span="24">
        <dynForm :info-form="searchForm" :search-tags="searchTags" >
          <el-button
            type="primary"
            icon="el-icon-search"
            @click="doSearch"
          >
            {{ $t("search") }}</el-button
            >
        </dynForm>
      </el-col>
    </el-row>
    <div class="table-buttons">
      <!-- v-btnPermission:edit -->
      <!-- <el-button
        type="primary"
        icon="el-icon-upload2"
      >{{ $t("import") }}</el-button
      > -->
      <el-button
        type="primary"
        icon="el-icon-download"
        @click="handleDownload"
      >{{ $t("export") }}</el-button
      >
    </div>
    <!-- 表单部分 -->
    <el-card shadow="never">
      <el-row>
        <dynTable
          ref="dynTable"
          :loading="tableLoading"
          :table-data="tableData"
          :table-columns="tableColumns"
          :handle-selection-change="handleSelectionChange"
          :row-click="rowClick"
        />
      </el-row>
      <pagination
        :total="total"
        :page.sync="listQuery.page"
        :size.sync="listQuery.size"
        @pagination="onChangePage"
      />
    </el-card>
  </div>
</template>

<script>
import mySetting from '@/mixins/mySetting'
import { getList } from '@/api/ruleConfig/waferSummary'
import { parseTime } from '@/utils'
import { mapGetters } from 'vuex'

export default {
  name: 'WaferSummary',
  mixins: [mySetting],
  data() {
    return {
      searchForm: {},
      searchTags: [
        { label: this.$t('calculationDate'), prop: '', tag: 'Dyndaterange', event: (value) => {
          this.searchForm.startDate = Array.isArray(value) ? value[0] : null
          this.searchForm.endDate = Array.isArray(value) ? value[1] : null
        } }
      ],
      tableColumns: [],
      tableColumnslisttem:
        [
          { prop: '', label: '', type: 'selection' },
          { prop: '', label: this.$t('index'), type: 'index', width: '50px', templete: (_scope) => {
            return (
              <span>{ (this.listQuery.page - 1) * this.listQuery.size + _scope.$index + 1 }</span>
            )
          } },
          { prop: 'dayNo', label: 'dayNo', width: '100px' },
          { prop: 'customerPN', label: 'dayNo', width: '160px' },
          { prop: 'productID', label: 'productID', width: '120px' },
          { prop: 'lotID', label: 'Lot ID', width: '100px' },
          { prop: 'waferID', label: 'Wafer ID', width: '120px' },
          { prop: 'testerName', label: 'Tester', width: '100px' },
          { prop: 'testProgram', label: 'ProgramName', width: '160px' },
          { prop: 'startTime', label: 'StartTime', width: '160px' },
          { prop: 'stopTime', label: 'EndTime', width: '160px' },
          { prop: 'passRate', label: 'Pass-RATE', width: '100px' },
          { prop: 'failRate', label: 'Fail-RATE', width: '100px' },
          { prop: 'totalQty', label: 'Total', width: '100px' },
          { prop: 'passQty', label: 'Pass-QTY', width: '100px' },
          { prop: 'failQty', label: 'Fail-QTY', width: '100px' },
          { prop: 'sblTrigger', label: 'SBL Trigger', width: '100px' },

          { prop: 'aoiFailRate', label: 'aoiFailRate', width: '100px' },
          { prop: 'bin2Count', label: 'BIN2', width: '100px' },
          { prop: 'bin3Count', label: 'BIN3', width: '100px' },
          { prop: 'patVersionName', label: 'PAT版本号', width: '160px' }
        ],
      tableLoading: false
    }
  },
  computed: {
    ...mapGetters(['baseApi'])
  },
  created() {
    this.initList()
  },
  methods: {
    async initList() {
      this.tableColumns = JSON.parse(JSON.stringify(this.tableColumnslisttem))
      const res = await getList(this.$clearNull({ ...this.listQuery, ...this.searchForm }))
      this.tableData = res.data[0].waferList
      this.total = res.total
      this.tableLoading = false
      // // patWaferarr数据整合
      // const patWaferarr = res.data.reduce((total, current) => {
      //   const { patWaferParamItemInfo } = current
      //   for (const [, value] of Object.entries(patWaferParamItemInfo)) {
      //     return total.concat(value)
      //   }
      // }, [])
      // // patWaferBinInfo
      // const patWaferBinInfo = res.data.reduce((total, current) => {
      //   const { patWaferBinInfo } = current
      //   for (const [, value] of Object.entries(patWaferBinInfo)) {
      //     return total.concat(value)
      //   }
      // }, [])
      // // cpWaferBinfo
      // const cpWaferBinfo = res.data.reduce((total, current) => {
      //   const { cpWaferBinInfo } = current
      //   for (const [, value] of Object.entries(cpWaferBinInfo)) {
      //     return total.concat(value)
      //   }
      // }, [])
      // // cpWaferParamItemInfo
      // const cpWaferParamItemInfo = res.data.reduce((total, current) => {
      //   const { cpWaferParamItemInfo } = current
      //   for (const [, value] of Object.entries(cpWaferParamItemInfo)) {
      //     return total.concat(value)
      //   }
      // }, [])

      // var tablecolumnslist = []
      // var tablecounmnslistcp = []
      // if (patWaferarr) {
      //   tablecolumnslist = patWaferarr.concat(patWaferBinInfo)
      // } else if (patWaferBinInfo) {
      //   tablecolumnslist = patWaferBinInfo.concat(patWaferarr)
      // }
      // if (cpWaferBinfo) {
      //   tablecounmnslistcp = cpWaferBinfo.concat(cpWaferParamItemInfo)
      // } else if (cpWaferParamItemInfo) {
      //   tablecounmnslistcp = cpWaferParamItemInfo.concat(cpWaferBinfo)
      // }

      const tablecolumnstemplate = []
      const tablecolumnstemplatecp = []
      // 剔除重复，并重新封装表头
      // tablecolumnslist.forEach((el) => {
      //   if (el.hasOwnProperty('paramName')) {
      //     if (tablecolumnstemplate.findIndex((item) => item.name === el.paramName) === -1) {
      //       tablecolumnstemplate.push({
      //         name: el['paramName'],
      //         RATE: el['paramName'] + '_RATE',
      //         QTY: el['paramName'] + '_QTY'
      //       })
      //     }
      //   } else if (el.hasOwnProperty('binCode')) {
      //     if (tablecolumnstemplate.findIndex((item) => item.name === el.binCode) === -1) {
      //       tablecolumnstemplate.push({
      //         name: el['binCode'],
      //         RATE: 'HBin' + el['binCode'] + '_RATE',
      //         QTY: 'HBin' + el['binCode'] + '_QTY'
      //       })
      //     }
      //   }
      // })
      // tablecounmnslistcp.forEach((el) => {
      //   if (el.hasOwnProperty('paramName')) {
      //     if (tablecolumnstemplatecp.findIndex((item) => item.name === el.paramName) === -1) {
      //       tablecolumnstemplatecp.push({
      //         name: el['paramName'],
      //         RATE: 'CP-' + el['paramName'] + '_RATE',
      //         QTY: 'CP-' + el['paramName'] + '_QTY'
      //       })
      //     }
      //   } else if (el.hasOwnProperty('binCode')) {
      //     if (tablecolumnstemplatecp.findIndex((item) => item.name === el.binCode) === -1) {
      //       tablecolumnstemplatecp.push({
      //         name: el['binCode'],
      //         RATE: 'CP-HBin' + el['binCode'] + '_RATE',
      //         QTY: 'CP-HBin' + el['binCode'] + '_QTY'
      //       })
      //     }
      //   }
      // })
      res.data[0].patWaferParamNameList.forEach((el) => {
        tablecolumnstemplate.push({
          name: el,
          RATE: el + '_RATE',
          QTY: el + '_QTY'
        })
      })
      res.data[0].patWaferBinList.forEach((el) => {
        tablecolumnstemplate.push({
          name: el,
          RATE: 'HBin' + el + '_RATE',
          QTY: 'HBin' + el + '_QTY'
        })
      })
      res.data[0].cpWaferParamNameList.forEach((el) => {
        tablecolumnstemplatecp.push({
          name: el,
          RATE: 'CP-' + el + '_RATE',
          QTY: 'CP-' + el + '_QTY'
        })
      })
      res.data[0].cpWaferBinList.forEach((el) => {
        tablecolumnstemplatecp.push({
          name: el,
          RATE: 'CP-HBin' + el + '_RATE',
          QTY: 'CP-HBin' + el + '_QTY'
        })
      })

      this.tableData.forEach((tableitem) => {
        // patWaferParamItemInfo
        if (Object.keys(tableitem.patWaferParamItemInfo).length !== 0) {
          tableitem.patWaferParamItemInfo.forEach((patitem) => {
            var index = tablecolumnstemplate.findIndex((el) => el.name === patitem.paramName)
            if (index !== -1) {
              var indexpatw = this.tableData.findIndex((el) => el.patID === tableitem.patID)

              this.tableData[indexpatw][tablecolumnstemplate[index].RATE] = patitem.failRate
              this.tableData[indexpatw][tablecolumnstemplate[index].QTY] = patitem.failDieCount
            }
          })
        }
        // patWaferBinInfo
        if (Object.keys(tableitem.patWaferBinInfo).length !== 0) {
          tableitem.patWaferBinInfo.forEach((patitem) => {
            var indexpatwaferbinfo = tablecolumnstemplate.findIndex((el) => el.name === patitem.binCode)
            if (indexpatwaferbinfo !== -1) {
              var indexpatwinfo = this.tableData.findIndex((el) => el.patID === tableitem.patID)

              this.tableData[indexpatwinfo][tablecolumnstemplate[indexpatwaferbinfo].RATE] = patitem.binRate
              this.tableData[indexpatwinfo][tablecolumnstemplate[indexpatwaferbinfo].QTY] = patitem.binCount
            }
          })
        }
        // cpWaferParamItemInfo
        if (Object.keys(tableitem.cpWaferParamItemInfo).length !== 0) {
          tableitem.cpWaferParamItemInfo.forEach((patitem) => {
            var indexcpWaferParamItemInfo = tablecolumnstemplatecp.findIndex((el) => el.name === patitem.paramName)
            if (indexcpWaferParamItemInfo !== -1) {
              var indexcpwa = this.tableData.findIndex((el) => el.patID === tableitem.patID)

              this.tableData[indexcpwa][tablecolumnstemplate[indexcpWaferParamItemInfo].RATE] = patitem.failRate
              this.tableData[indexcpwa][tablecolumnstemplate[indexcpWaferParamItemInfo].QTY] = patitem.failDieCount
            }
          })
        }
        // cpWaferParamItemInfo
        if (Object.keys(tableitem.cpWaferBinInfo).length !== 0) {
          tableitem.cpWaferBinInfo.forEach((patitem) => {
            var indexcpwabin = tablecolumnstemplatecp.findIndex((el) => el.name === patitem.paramName)
            if (indexcpwabin !== -1) {
              var indexcpwabinfo = this.tableData.findIndex((el) => el.patID === tableitem.patID)

              this.tableData[indexcpwabin][tablecolumnstemplate[indexcpwabinfo].RATE] = patitem.binRate
              this.tableData[indexcpwabin][tablecolumnstemplate[indexcpwabinfo].QTY] = patitem.binCount
            }
          })
        }
      })
      // console.log(tablecolumnstemplate)
      // const arr1 = []
      // const arr = patWaferarr.reduce((total, current) => {
      //   console.log(current)
      //   if (!total.includes(current.paramName)) {
      //     arr1.push({ prop: '', label: current.paramName, width: '100px', templete: () => {
      //       return (
      //         <span>{ current.failRate }</span>
      //       )
      //     } })
      //     return total.concat([current.paramName])
      //   } else {
      //     return total
      //   }
      // }, [])
      // console.log(patWaferarr)
      tablecolumnstemplate.forEach((el) => {
        this.tableColumns.push({ prop: el.RATE, label: el.RATE, width: '100px' })
        this.tableColumns.push({ prop: el.QTY, label: el.QTY, width: '100px' })
      })
      tablecolumnstemplatecp.forEach((el) => {
        this.tableColumns.push({ prop: el.RATE, label: el.RATE, width: '100px' })
        this.tableColumns.push({ prop: el.QTY, label: el.QTY, width: '100px' })
      })
    },
    doSearch() {
      this.listQuery.page = 1
      this.initList()
    },
    async handleDownload() {
      const res = await getList(this.$clearNull({ ...this.listQuery, ...this.searchForm, toexcel: 1 }))
      window.open(this.baseApi + '/' + res.data)
    },
    formatJson(filterVal, jsonData) {
      return jsonData.map(v => filterVal.map(j => {
        if (j === 'timestamp') {
          return parseTime(v[j])
        } else {
          return v[j]
        }
      }))
    },
    handleSelectionChange(row) {
      this.multipleSelection = row
    },
    rowClick(row) {
      this.$refs.dynTable.$refs.multipleTable.toggleRowSelection(row)
    },
    onChangePage(page) {
      this.listQuery = page
      this.initList()
    }
  }
}
</script>

<style scoped lang="scss">
@import "~@/assets/styles/defaultStyle.scss";
</style>
